package com.yuyang.wifi.utils.network;

import com.yuyang.wifi.constant.ApiConstant;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.GetBuilder;
import com.zhy.http.okhttp.request.RequestCall;

import java.util.ArrayList;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;

/**
 * Created by WangCe on 2016/4/4.
 */
public class HttpManager {
    private Retrofit retrofit;
    private OkHttpClient okHttpClient;
    private static ClientApi clientApi;
    private static HttpManager httpService;


    public static HttpManager getInstance() {
        if (httpService == null) {
            synchronized (HttpManager.class) {
                if (httpService == null) {
                    httpService = new HttpManager();
                }
            }
        }
        return httpService;
    }

    private HttpManager() {
        Interceptors headerConstructor = new Interceptors();
        OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
        ArrayList<Interceptor> interceptors = headerConstructor.getInterceptors();
        for (Interceptor interceptor : interceptors) {
            builder.addInterceptor(interceptor);
        }
        okHttpClient = builder
                .retryOnConnectionFailure(true)
                .build();
        retrofit = new Retrofit.Builder()
                .baseUrl(ApiConstant.URLPREFIX)
                .addConverterFactory(FastJsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(okHttpClient)
                .build();
        clientApi = retrofit.create(ClientApi.class);
    }


    public OkHttpClient getOkHttpClient() {
        return okHttpClient;
    }

    public ClientApi getApi() {
        return clientApi;
    }

    public static HttpManager getHttpService() {
        return httpService;
    }

    public static void requestCheckGoodsId(String url, Callback<String> callback) {
        GetBuilder getBuilder = OkHttpUtils.get();
        RequestCall call = getBuilder.url(url).build();
        call.execute((com.zhy.http.okhttp.callback.Callback) callback);
    }
}
